package com.mall.sun.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mall.sun.model.dto.VerifyCodeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.UUID;

/**
 * description:  <br>
 * date: 2021/12/16 16:09 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 */
@Component
public class KaptchaUtil {
    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    RedisUtil redisUtil;

    public VerifyCodeDTO getRandomCodeBase64() {
        String randomStr = defaultKaptcha.createText();
        System.out.println(randomStr);
        String uuid = UUID.randomUUID().toString();
        redisUtil.set(uuid,randomStr);
        redisUtil.expire(uuid,60);
        String base64String = "data:image/jpg;base64,";
        BufferedImage image = defaultKaptcha.createImage(randomStr);
        try {
            //  直接返回图片
            //  ImageIO.write(image, "PNG", response.getOutputStream());
            //返回 base64
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(image, "JPG", bos);

            byte[] bytes = bos.toByteArray();
            Base64.Encoder encoder = Base64.getEncoder();
            base64String = base64String + encoder.encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new VerifyCodeDTO().setUuid(uuid).setBase64Img(base64String);
    }

}
